package sunwul.datasource.config;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;
import sunwul.datasource.common.FactoryUtil_springTran;

import javax.sql.DataSource;

/*****
 * @author sunwul
 * @date 2022/2/25 11:27
 * @description
 * * 指定扫描的包
 * * 指定使用的sqlSessionFactory
 */
@Configuration
@MapperScan(basePackages = "sunwul.datasource.mapper.write", sqlSessionFactoryRef = "sqlSessionFactory_w")
public class Write_MybatisConfig_springTran {

    /**
     * 写库数据源
     *
     * @return DataSource
     */
    @Bean("dataSource_write")
    @ConfigurationProperties(prefix = "spring.datasource.datasource-write")
    public DataSource dataSource_write() {
        System.out.println("==============读取配置信息,创建DataSource=============");
        // 通过绑定全局配置,拿到属性后自动创建一个DruidDataSource
        return DruidDataSourceBuilder.create().build();
    }

    /**
     * 配置写库的 SqlSessionFactory
     * 整合
     *
     * @return SqlSessionFactory
     * @throws Exception ex
     */
    @Bean
    @Primary
    public SqlSessionFactory sqlSessionFactory_w() throws Exception {
        return FactoryUtil_springTran.createFactory(dataSource_write(), "classpath:mapper/write/*Mapper_springTran.xml", true);
    }

    /**
     * 写库的事务管理
     *
     * @return DataSourceTransactionManager
     */
    @Bean
    @Primary
    public DataSourceTransactionManager dataSourceTransactionManager_w() {
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
        dataSourceTransactionManager.setDataSource(dataSource_write());
        return dataSourceTransactionManager;
    }

    /**
     * 事务模板  -  Spring编程式事务
     *
     * @return TransactionTemplate
     */
    @Bean
    public TransactionTemplate transactionTemplate_w() {
        return new TransactionTemplate(dataSourceTransactionManager_w());
    }

}
